package ex3.render.raytrace;

import java.util.Map;
import math.Point3D;
import math.Vec;

public class SpotLight extends Light
{
    protected Point3D pos;
    protected Vec dir;
    protected double kc;
    protected double kl;
    protected double kq;

    public SpotLight()
    {
        pos = new Point3D(0.0D, 0.0D, 0.0D);
        color = new Vec(1.0D, 1.0D, 1.0D);
        kc = 1.0D;
        kl = 0.0D;
        kq = 0.0D;
    }

    public void init(@SuppressWarnings("rawtypes") Map attributes)
    {
        super.init(attributes);
        if(attributes.containsKey("pos"))
            pos = new Point3D((String)attributes.get("pos"));
        if(attributes.containsKey("dir"))
        {
            dir = new Vec((String)attributes.get("dir"));
            dir.normalize();
        }
        if(attributes.containsKey("kc"))
            kc = (new Double((String)attributes.get("kc"))).doubleValue();
        if(attributes.containsKey("kl"))
            kl = (new Double((String)attributes.get("kl"))).doubleValue();
        if(attributes.containsKey("kq"))
            kq = (new Double((String)attributes.get("kq"))).doubleValue();
    }

    public Vec getColor(Point3D at)
    {
        Vec L = pos.sub(at);
        double dist = L.length();
        L.normalize();
        double LD = -L.dotProd(dir);
        if(LD <= 0.0D)
        {
            return new Vec(0.0D, 0.0D, 0.0D);
        } else
        {
            Vec ret = color.clone();
            ret.scale(LD / (kc + kl * dist + kq * dist * dist));
            return ret;
        }
    }

    public Vec getDirection(Point3D at)
    {
        Vec L = pos.sub(at);
        L.normalize();
        return L;
    }

    public double getShadow(Point3D at, double minIntersectionDist)
    {
        Vec L = pos.sub(at);
        double lightDist = L.length();
        return minIntersectionDist <= 0.0001D || minIntersectionDist >= lightDist - 0.0001D ? 1.0D : 0.0D;
    }
}